package qiniu

import (
	"context"
	"fmt"
	"github.com/qiniu/go-sdk/v7/auth/qbox"
	"github.com/qiniu/go-sdk/v7/storage"
	"tdy-backend/global"
)

type Qiniu struct {
	Instance *qbox.Mac
}

func NewQiniu() *Qiniu {
	instance := &Qiniu{}
	return instance.SetConfig()
}

//上传
func (o *Qiniu) Upload(filepath string, filename string) (string, error) {
	config := global.TYD_CONFIG
	token := o._getToken(config.GetString("file.config.bucket"))
	cfg := storage.Config{}
	// 空间对应的机房
	//cfg.Zone = &storage.ZoneHuadong
	cfg.Zone, _ = storage.GetRegion(global.TYD_CONFIG.GetString("file.config.ak"), global.TYD_CONFIG.GetString("file.config.bucket"))
	// 是否使用https域名
	cfg.UseHTTPS = global.TYD_CONFIG.GetBool("file.config.isHttps")
	// 上传是否使用CDN上传加速
	cfg.UseCdnDomains = global.TYD_CONFIG.GetBool("file.config.isCdnUpload")

	// 构建表单上传的对象
	formUploader := storage.NewFormUploader(&cfg)
	ret := storage.PutRet{}
	err := formUploader.PutFile(context.Background(), &ret, token, filename, filepath, nil)
	if err != nil {
		global.TYD_LOGGER.Error(err.Error())
		return "", err
	}
	fmt.Println(ret.Key, ret.Hash)
	return ret.Key, nil
}

//配置
func (o *Qiniu) SetConfig() *Qiniu {
	config := global.TYD_CONFIG
	accessKey := config.GetString("file.config.ak")
	secretKey := config.GetString("file.config.sk")
	o.Instance = qbox.NewMac(accessKey, secretKey)
	return o
}

//上传凭证获取
func (o *Qiniu) _getToken(bucket string) string {
	putPolicy := storage.PutPolicy{
		Scope: bucket,
	}
	upToken := putPolicy.UploadToken(o.Instance)
	return upToken
}
func (o *Qiniu) GetUrl(key string) string {
	domain := global.TYD_CONFIG.GetString("file.config.domain")
	return domain + key
}
